package com.douwong.student.fragment;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;

import com.douwong.student.R;
import com.douwong.student.adapter.ClassFileAdapter;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.contant.CommonConfig;
import com.douwong.student.interfaces.WorkResultNotify;
import com.douwong.student.model.ClassFile;
import com.douwong.student.model.ClassFileBean;
import com.douwong.student.model.RequestAction;
import com.douwong.student.popuwindow.UpLoadPopuWindow;
import com.douwong.student.task.ClassFileTask;
import com.douwong.student.utils.ToastUtils;
import com.douwong.student.utils.UIUtils;
import com.douwong.student.view.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;


/*
课堂文件
 */
@SuppressLint("ValidFragment")
public abstract class ClassFileFragment extends Fragment {

	private PullToRefreshListView list_view;
	private ClassFileAdapter adapter;
	private View view;
	private int visibleLastIndex = 0, currentPageIndex = 1;
	private ArrayList<ClassFileBean> list = new ArrayList<ClassFileBean>();
	private BaseApplication app;
	private boolean isRefreshing = false;
	private String startTime = null;
	private String endTime = null;
	private String fileType;
	private String subjectId=null;
    private ImageView statue_img;
    private UpLoadPopuWindow popu;
    private boolean isFirst=true;
	private ClassFileTask mTask;

	abstract String getFileType();
	Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what==0){
				popu.showAtLocation(getView(), Gravity.CENTER,0,0);
				popu.setText("加载中...");
				initData(RequestAction.INIT, 1,false);
			}else if(msg.what==1){
				if(popu!=null&&popu.isShowing()){
					popu.dismiss();
				}
				list_view.onRefreshComplete();
//				adapter.notifyDataSetChanged();
			}
		};
	};
	BroadcastReceiver receiver=new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(CommonConfig.CLASSFILE_SEARCH)){
				startTime=intent.getStringExtra("start_time");
				endTime=intent.getStringExtra("end_time");
				subjectId=intent.getStringExtra("subjectId");
				list.clear();
				adapter.notifyDataSetChanged();
//				popu.showAtLocation(getView(), Gravity.CENTER,0,0);
//				popu.setText("加载中...");
				initData(RequestAction.REFRESH, 1,true);
				statue_img.setVisibility(View.INVISIBLE);
				
			}
		}
	};
	IntentFilter filter=new IntentFilter(){
		{addAction(CommonConfig.CLASSFILE_SEARCH);}
	};
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = LayoutInflater.from(getActivity()).inflate(R.layout.black_board, null);
		popu=new UpLoadPopuWindow(getActivity());
		list_view = (PullToRefreshListView) view.findViewById(R.id.class_file_listview);
		getActivity().registerReceiver(receiver, filter);
		adapter = new ClassFileAdapter(list, getActivity());
		list_view.setAdapter(adapter);
		statue_img=(ImageView) view.findViewById(R.id.statue_img);
		app = (BaseApplication) getActivity().getApplication();
		fileType = getFileType();//1，课堂笔记 2，小黑板
		if(fileType.equals("2")){
			handler.sendEmptyMessageDelayed(0, 500);
		}else{
			initData(RequestAction.INIT, 1,false);
		}
//		initData(RequestAction.INIT, 1,false);
		list_view.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {

			@Override
			public void onRefresh() {
				initData(RequestAction.REFRESH, 1,false);
			}
		});


/*
		list_view.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				list_view.onScrollStateChanged(view, scrollState);
				if (isRefreshing)
					return;
				int lastItemIndex = adapter.getCount();
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastItemIndex) {

					if (30 * (currentPageIndex) <= adapter.getCount()) {
						++currentPageIndex;
						initData(RequestAction.LOADMROE, currentPageIndex,false);
						isRefreshing = true;
					}
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				list_view.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
				visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
			}
		});*/


		list_view.setOnILoadMoreListener(new PullToRefreshListView.OnILoadMoreListener() {
			@Override
			public void onLoadMore() {

				 if (isRefreshing) {
                    return;
                }
                ++currentPageIndex;
				initData(RequestAction.LOADMROE, currentPageIndex,false);
                isRefreshing = true;

			}
		});
		list_view.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				if (!fileType.equals("3")) {
					// openFile(list.get(arg2-1));
				} else {
					// startActivity(getVideoFileIntent(list.get(arg2-1).getResInfoBean().getResExt().getDownloadUrl()));
				}

			}
		});
		return view;
	}
	
	private void initData(final RequestAction action, int pageIndex,boolean isSearch) {
		// 加载更多时，出现异常或者没有多余数据，要将currentPageIndex回到加载数据前的一页
		// 其他访问类型均需要清空当前数据，重新显示，加载更多是在原有的数据上增加
		// list.addAll(arryResult);
		mTask = new ClassFileTask(isSearch,action, new WorkResultNotify<ClassFile>() {

			@Override
			public void notify(int stateCode, List<ClassFile> arryResult) {

				if (ClassFileTask.NO_DATA == stateCode) {
					if(popu!=null&&popu.isShowing()){
						popu.dismiss();
					}
					if (RequestAction.REFRESH==action){
					statue_img.setVisibility(View.VISIBLE);
					statue_img.setImageResource(R.mipmap.no_record);
					}
					if (RequestAction.LOADMROE ==action){
						ToastUtils.makeText(UIUtils.getContext(),"没有数据了");
					}


					// 加载更多时，出现异常或者没有多余数据，要将currentPageIndex回到加载数据前的一页
					if (currentPageIndex > 1 && RequestAction.LOADMROE == action) {
						--currentPageIndex;
					}
					if (arryResult == null && action != RequestAction.LOADMROE) {
						list.clear();
					}

				} else if (ClassFileTask.REQUESTOK == stateCode) {
					statue_img.setVisibility(View.INVISIBLE);
					// 其他访问类型均需要清空当前数据，重新显示，加载更多是在原有的数据上增加
					if (RequestAction.LOADMROE != action) {
						list.clear();
					}

					ArrayList<ClassFileBean> tem = new ArrayList<ClassFileBean>();
					if (arryResult != null && arryResult.size() > 0) {
						for (int i = 0; i < arryResult.size(); i++) {
							ClassFileBean bean = new ClassFileBean();
							String time = arryResult.get(i).getCreateTime().substring(0, 10);
							bean.setCreateTime(time);
							bean.getList().add(arryResult.get(i));
							for (int j = i + 1; j < arryResult.size(); j++) {
								String temp = arryResult.get(j).getCreateTime().substring(0, 10);
								if (time.equals(temp)) {
									bean.getList().add(arryResult.get(j));
								};
							}
							if (i == 0) {
								list.add(bean);
							} else {
								boolean isExit = false;
								for (int k = 0; k < list.size(); k++) {
									if (bean.getCreateTime().equals(list.get(k).getCreateTime())) {
										isExit = true;
									} 
								}
								if (!isExit) {
									list.add(bean);
								}
							}
						}
						// list.addAll(arryResult);
					}else{
						statue_img.setVisibility(View.VISIBLE);
						statue_img.setImageResource(R.mipmap.no_record);
					}
				}else if(ClassFileTask.NO_NETWOK == stateCode){
					list.clear();
					statue_img.setVisibility(View.VISIBLE);
					statue_img.setImageResource(R.mipmap.no_wifi);
				}
				if(isFirst){
					isFirst=false;
					handler.sendEmptyMessageDelayed(1, 2000);
				}else{
					list_view.onRefreshComplete();

				}
				

				isRefreshing = false;
				list_view.completeLoadMore();
				list_view.onRefreshComplete();

				adapter.notifyDataSetChanged();
			}
		}, app);
		if(BaseApplication.sUserBean!=null){

			mTask.execute(fileType, subjectId, startTime, endTime, String.valueOf(pageIndex));
		}else{
			statue_img.setVisibility(View.VISIBLE);
			statue_img.setImageResource(R.mipmap.no_record);
			isRefreshing = false;
			if(isFirst){
				isFirst=false;
				handler.sendEmptyMessageDelayed(1, 2000);
			}else{
				list_view.onRefreshComplete();
			}
		}
		
	}


	// android获取一个用于打开视频文件的intent
	public Intent getVideoFileIntent(String url) {
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("oneshot", 0);
		intent.putExtra("configchange", 0);
		Uri uri = Uri.parse(url);
		intent.setDataAndType(uri, "video/*");
		return intent;
	}
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		getActivity().unregisterReceiver(receiver);

		if (popu!=null && popu.isShowing()){
			popu.dismiss();
		}
		if (mTask!=null && !mTask.isCancelled()){
			mTask.cancel(true);
		}


	}

}
